package com.edais.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.edais.dao.GeTuiDao;
import com.edais.service.GeTuiService;
import com.edais.util.Consts;
import com.edais.util.StringUtil;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultDTO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service

public class GeTuiServiceImpl implements GeTuiService {
	
	private static final Log logger = LogFactory
			.getLog(GeTuiServiceImpl.class);
	
	@Autowired
	private GeTuiDao geTuiDao;
	
	/**
	 * 保存手机设备信息
	 */
	@Override
	public ResultDTO saveMobileInfo(JSONObject params) {
				

		JSONObject respJson = new JSONObject();
		
		//根据CID查询手机设备信息
		Map<String,String> queryParam = new HashMap<>();
		queryParam.put("cid",params.getString("cid"));
		List<Map<String, Object>> results = geTuiDao.queryUserIdByDeviceNum(queryParam);
		
		String userId = params.getString("userId");
		//若参数userId为空,设置默认值为0
		if(StringUtil.isEmpty(userId)){
			userId = "0";
			params.put("userId", userId);
		}
		
		if(results == null || results.size() <= 0){

			Map<String,String> saveParam = new HashMap<>();
			saveParam.put("cid",params.getString("cid"));
			saveParam.put("userId",params.getString("userId"));
			geTuiDao.saveMobileInfo(saveParam);

			logger.info("-------------------------------- GeTuiServiceImpl saveMobileInfo() geTuiDao.saveMobileInfo() 添加手机设备信息 --------------------------------");
						
			return new ResultDTO(ResultCode.SUCCESS,"手机设备信息保存成功!");
		}
		
		Map<String, Object> result = results.get(0);
					
		String qUserId = String.valueOf(result.get("USERID"));
		//参数userId与查询出userId不一致
		if(!userId.equals(qUserId)){
			//更新手机设备信息
			Map<String,String> updateParam = new HashMap<>();
			updateParam.put("cid",params.getString("cid"));
			updateParam.put("userId",params.getString("userId"));
			geTuiDao.updateMobileInfo(updateParam);
			
			logger.info("-------------------------------- GeTuiServiceImpl saveMobileInfo() geTuiDao.updateMobileInfo() userId=" + userId 
					+ " , qUserId=" + qUserId + " 更新手机设备信息 --------------------------------");
		}

		return new ResultDTO(ResultCode.SUCCESS,"手机设备信息保存成功!");
	}
}
